/* 
	Copyright 2012 Atif Farrukh

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.*/
   
package com.atiffarrukh.get.inspired;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.SubMenu;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.TranslateAnimation;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends SherlockActivity{
	public static final String PREFS_NAME = "MyPrefsFile";
	String[] quotes;
	String[] authors;
	int count = 0;
	TextView quote,author;
	static int animationDuration = 600;
	private SharedPreferences counterSaver;
	GestureDetector gestureDetector;
	private static int MOVE = 70;
	private String notConnected = "You are not connected to any Network"; 
	//final String to = "atiffarrukh@gmail.com";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		quote = (TextView) findViewById(R.id.textView1);
		author = (TextView) findViewById(R.id.textView2);
		counterSaver = PreferenceManager.getDefaultSharedPreferences(this);
		count = counterSaver.getInt("countValue", 0);

		Log.d("Main Activity", "count is " + count);
		quotes = getResources().getStringArray(R.array.quotesArray);
		authors = getResources().getStringArray(R.array.authorsArray);

		//String[] quotes = getResources().getStringArray(R.array.quotesArray);
		quote.setText(quotes[count]);
		author.setText(authors[count]);

		Typeface authorsTypeface = Typeface.createFromAsset(getAssets(), "font/Barrista-Regular.otf");
		author.setTypeface(authorsTypeface);
		Typeface quotesTypeface = Typeface.createFromAsset(getAssets(), "font/Angostura.ttf");
		quote.setTypeface(quotesTypeface);

		gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
			public boolean onDown(MotionEvent e){
				Log.d("onDown", "touched screen");
				return true;
			}

			public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
				Log.d("onFiling", "y-axis diff = "+( e2.getY()-e1.getY()));
				Log.d("onFiling", "x-axis diff = "+( e2.getX()-e1.getX()));
				if (e1.getX() - e2.getX() > MOVE ) {
					count++;
					if(count >= quotes.length){
						count = 0;
						return true;
					}
					else{
						Log.d("onFiling", "Swipe Increment");
						animateIncrement(count);
						return true;
					}
				}else if (e1.getX() - e2.getX() < MOVE) {
					count--;
					if(count < 0){
						show();
						count = 0;
						return true;
					}
					else{
						Log.d("onFiling", "Swipe Decrement");
						animateDecrement(count);
						return true;
					}
				}
				else return true;
			}
		});

		/*        quote.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				count++;
				if(count >= quotes.length)
					count = 0;
				else
					animate(count);
			}
		});*/



	}

	protected void show() {
		// TODO Auto-generated method stub
		Toast.makeText(this, "Please Swipe Left to second quote", Toast.LENGTH_SHORT).show();
	}

	protected void animateDecrement(final int count2) {
		// TODO Auto-generated method stub
		Log.d("TAG", "This is animateDecrement and count :" + count);
		//AlphaAnimation animation = new AlphaAnimation(1.0f, 0.0f);
		Log.d("TAG", "anim set: " + quotes[count]);
		TranslateAnimation anim = new TranslateAnimation(0, 1000, 0, 0);
		anim.setDuration(550);
		anim.setAnimationListener(new AnimationListener() {

			public void onAnimationStart(Animation arg0) {
				// TODO Auto-generated method stub

			}

			public void onAnimationRepeat(Animation arg0) {
				// TODO Auto-generated method stub

			}

			public void onAnimationEnd(Animation arg0) {
				// TODO Auto-generated method stub
				TranslateAnimation anim = new TranslateAnimation(-1000, 0, 0, 0);
				anim.setDuration(550);
				quote.startAnimation(anim);

				TranslateAnimation animNew = new TranslateAnimation(0, 1000, 0, 0);
				animNew.setDuration(400);
				animNew.setAnimationListener(new AnimationListener() {

					public void onAnimationStart(Animation arg0) {
						// TODO Auto-generated method stub
						quote.setText(quotes[count2]);

					}

					public void onAnimationRepeat(Animation arg0) {
						// TODO Auto-generated method stub

					}

					public void onAnimationEnd(Animation arg0) {
						// TODO Auto-generated method stub
						TranslateAnimation animNew1 = new TranslateAnimation(-1000, 0, 0, 0);
						animNew1.setDuration(300);
						author.startAnimation(animNew1);
						author.setText(authors[count2]);
					}
				});
				author.startAnimation(animNew);

				/*AlphaAnimation animation = new AlphaAnimation(1.0f, 0.0f);
			animation.setDuration(300);
			tv.startAnimation(animation);*/
			}
		});
		quote.startAnimation(anim);
	}

	protected void animateIncrement(final int count2) {
		// TODO Auto-generated method stub
		Log.d("TAG", "This is animateIncrement and count :" + count);
		//AlphaAnimation animation = new AlphaAnimation(1.0f, 0.0f);
		Log.d("TAG", "anim set: " + quotes[count]);
		TranslateAnimation anim = new TranslateAnimation(0, -1000, 0, 0);
		anim.setDuration(800);
		anim.setAnimationListener(new AnimationListener() {

			public void onAnimationStart(Animation arg0) {
				// TODO Auto-generated method stub

			}

			public void onAnimationRepeat(Animation arg0) {
				// TODO Auto-generated method stub

			}

			public void onAnimationEnd(Animation arg0) {
				// TODO Auto-generated method stub
				TranslateAnimation anim = new TranslateAnimation(1000, 0, 0, 0);
				anim.setDuration(800);
				quote.startAnimation(anim);

				TranslateAnimation animNew = new TranslateAnimation(0, -1000, 0, 0);
				animNew.setDuration(600);
				animNew.setAnimationListener(new AnimationListener() {

					public void onAnimationStart(Animation arg0) {
						// TODO Auto-generated method stub

					}

					public void onAnimationRepeat(Animation arg0) {
						// TODO Auto-generated method stub

					}

					public void onAnimationEnd(Animation arg0) {
						// TODO Auto-generated method stub
						TranslateAnimation animNew1 = new TranslateAnimation(1000, 0, 0, 0);
						animNew1.setDuration(400);
						author.startAnimation(animNew1);
						author.setText(authors[count2]);
					}
				});
				author.startAnimation(animNew);
				quote.setText(quotes[count2]);
				/*AlphaAnimation animation = new AlphaAnimation(1.0f, 0.0f);
			animation.setDuration(300);
			tv.startAnimation(animation);*/
			}
		});
		quote.startAnimation(anim);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		menu.add("Rate it");
		menu.add("Reset Quotes");
		menu.add("Contact");

		SubMenu subMenu1 = menu.addSubMenu("Share");
		subMenu1.add("SMS");
		subMenu1.add("Facebook");
		subMenu1.add("Google Plus");
		subMenu1.add("Email");
		MenuItem subMenu1Item = subMenu1.getItem();
		subMenu1Item.setIcon(R.drawable.ic_title_share_default);
		subMenu1Item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);


		return super.onCreateOptionsMenu(menu);
	}

	private boolean isConntected() {
		// TODO Auto-generated method stub
		boolean isConntected = true;
		NetworkInfo activeNetwork;
		ConnectivityManager cm;
		Log.d("Check ", "isConnected()");
		try{
			cm = (ConnectivityManager) this.getSystemService(CONNECTIVITY_SERVICE);
			activeNetwork = cm.getActiveNetworkInfo();
			isConntected = activeNetwork.isConnected();
		}catch(RuntimeException e){
			isConntected = false;
			Toast.makeText(this,notConnected, Toast.LENGTH_LONG).show();
			return isConntected;
		}

		Log.d("Check ", "Value of isConnected == " + isConntected);
		return isConntected;

	}


	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		if(item.getTitle().equals("Rate it")){
			Uri uri = Uri.parse("market://details?id=com.atiffarrukh.get.inspired");
			Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
			try {
				startActivity(goToMarket);
			} catch (ActivityNotFoundException e) {
				Toast.makeText(getBaseContext(), "Couldn't launch the market", Toast.LENGTH_LONG).show();
			}
		}
		else if(item.getTitle().equals("Contact")){
			Intent i = new Intent(this,ContactDialog.class );
			startActivity(i);
		} 
		else if(item.getTitle().equals("Reset Quotes")){
			SharedPreferences.Editor editor = counterSaver.edit();
			count = 0;
			quote.setText(quotes[count]);
			author.setText(authors[count]);
			editor.putInt("countValue", 0);
			editor.commit();
		}

		else if(item.getTitle().equals("Facebook")){
			if(isConntected()){
				Intent facebookIntent = new Intent(this, FacebookLogIn.class);
				Bundle bundle = new Bundle();
				String postString = quotes[count] +  "\n" + authors[count];
				bundle.putString("postValue", postString);
				facebookIntent.putExtras(bundle);
				startActivity(facebookIntent);
			}

			//Toast.makeText(getApplicationContext(), "This is TOAST count = " + count, Toast.LENGTH_SHORT).show();
		}
		else if(item.getTitle().equals("Google Plus")){
			if(isConntected()){
				Intent googlePlusIntent = new Intent(this, GooglePlusLogInandPost.class);
				Bundle bundle = new Bundle();
				String postString = quotes[count] + "\n" + authors[count];
				bundle.putString("postValue", postString);
				googlePlusIntent.putExtras(bundle);
				startActivity(googlePlusIntent);
			}

		}else if(item.getTitle().equals("SMS")){
			Intent smShare = new Intent(this, SmShare.class);
			Bundle bundle = new Bundle();
			String postString = quotes[count] + "\n" + authors[count];
			bundle.putString("postValue", postString);
			smShare.putExtras(bundle);
			startActivity(smShare);
			//Toast.makeText(getApplicationContext(), "This is TOAST", Toast.LENGTH_SHORT).show();
		}else if(item.getTitle().equals("Email")){


			Intent email = new Intent(Intent.ACTION_SEND);
			//email.putExtra(Intent.EXTRA_EMAIL, new String[]{ to});
			//email.putExtra(Intent.EXTRA_CC, new String[]{ to});
			//email.putExtra(Intent.EXTRA_BCC, new String[]{to});
			email.putExtra(Intent.EXTRA_TEXT, quotes[count] + "\n" + authors[count]);

			//need this to prompts email client only
			email.setType("message/rfc822");

			startActivity(Intent.createChooser(email, "Choose an Email client :"));
			//Toast.makeText(getApplicationContext(), "This is TOAST", Toast.LENGTH_SHORT).show();
		}

		return  super.onOptionsItemSelected(item);
	}


	/*@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
        quote.setText(quotes[count]);
        author.setText(authors[count]);
	}*/

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		Log.d("Saving", count + " onPause");
		SharedPreferences.Editor editor= counterSaver.edit();
		editor.putInt("countValue", count);
		editor.commit();
		//finish();
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		return gestureDetector.onTouchEvent(event);
	}
}
